package com.atguigu.tingshu.user.logins.environment;

import com.atguigu.tingshu.user.logins.annotation.MyLoginType;
import com.atguigu.tingshu.user.logins.strategy.KindsLogin;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * title:
 * author: zgl
 * date: 2024/2/27
 * description：
 */
@Component
public class LoginClient implements ApplicationContextAware {
    private static final ConcurrentHashMap<String, KindsLogin> map = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beansMap = applicationContext.getBeansWithAnnotation(MyLoginType.class);
        //为空直接返回
        if (CollectionUtils.isEmpty(beansMap)) {
            return;
        }
        //获取beans
        Collection<Object> beans = beansMap.values();
        if (CollectionUtils.isEmpty(beans)) {
            return;
        }
        beans.forEach(bean -> {
            String type = bean.getClass().getAnnotation(MyLoginType.class).value().type;
            KindsLogin kindsLogin = (KindsLogin) bean;
            map.put(type, kindsLogin);
        });
    }

    public Map<String, Object> login(String type, Map<String, Object> paramMap) {
        return map.get(type).login(paramMap);
    }
}
